/**
 * created by zhouli on 2019/1/9
 * 注意这块有一个级联关系
 * 组织权限的id挂在 授权策略对象上
 * 授权策略--组织权限--组织权限类型
 * 组织权限根据不同角色分为三种：管理员的组织权限 | 财务的组织权限 | 其他的组织权限
 * 每一种组织权限类型分为两种：全租户 公司 | 全租户 部分 | 全租户 部分
 */
import React from 'react';
import {connect} from 'react-redux';
import {Menu, Icon, Modal, Button, Input, Select, Alert, message, Switch, Radio} from 'antd';
import {deepCopy, uniquelizeArray, messages} from 'share/common';
import POService from 'containers/permission-setting/role-permission-setting/role-permission-detail/components/permission-org/permission-org.service';
import 'styles/permission-setting/role-permission-setting/role-permission-detail/components/permission-org/permission-org.scss';
//需要在这个里面去配置弹窗类型
import chooserData from 'share/chooserData';
//规则添加组件
import RuleInfo from 'containers/permission-setting/role-permission-setting/role-permission-detail/components/permission-org/rule-info';
import ListSelector from 'components/list-selector.js';

const Option = Select.Option;
const SubMenu = Menu.SubMenu;
const Search = Input.Search;
const confirm = Modal.confirm;
const radioStylePermissionOrg = {
  display: 'block',
  height: '30px',
  lineHeight: '30px',
};
const RadioGroup = Radio.Group;

class PermissionOrg extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      orgPermissionDetail: {},//组织权限详情
      conditionViewDTOS: [],//规则组数据
      defaultConditionViewDTO: {
        "isEditing": true,//正在编辑的标志
        "conditionDetails": [
          {
            "conditionProperty": "Department",
            "conditionLogic": "I",
            "enabled": true,
            "conditionValues": []
          },
          {
            "conditionProperty": "Company",
            "conditionLogic": "I",
            "enabled": true,
            "conditionValues": []
          },
        ]
      },//默认的一个规则，新增的时候，直接调用这个
      conditionCloneForCancel: false,//点击编辑时，拷贝一份取消的时候用,一旦取消设置为false
      //点击添加条件中的项目弹窗
      extraParams: {//弹窗额外的参数
        excludeList: [],
        systemCustomEnumerationType: "",// systemCustomEnumerationType 代表类型，1001 type,1002 duty , 1008 级别
        status: ""
      },
      selectorItem: chooserData['personTypeModel'],//弹窗显示配置
      showListSelector: false,//弹窗是否显示
      saveLoading: false,
    };
    // 正在编辑条件
    this.editingRule = {
      name: "",// 正在编辑条件里面项目名称：Department
      index: "",    // 正在编辑条件序号
      itemIndex: "" // 正在编辑条件里面项目序号
    };
  }

  componentDidMount() {
    this.getPermissionTableItemDetail();
  }

  //id获取组织权限详情
  getPermissionTableItemDetail = () => {
    let params = {
      "permissionId": this.props.policyData.orgPermissionId,
    };
    //根据路径上的oid,查出该条完整数据
    POService.getPermissionTableItemDetail(params)
      .then((response) => {
        this.setState({
          orgPermissionDetail: response.data,
          conditionViewDTOS: [response.data]//当组织权限类型是 OTHER 的时候显示条件
        })
      })
  };
  //分为新增条件与修改条件
  confirmRuleHandle = (i) => {
    const {conditionViewDTOS} = this.state;
    if (this._checkCoditionIsEmpty(conditionViewDTOS[i])) {
      let pureCondition = this._deleteEmptyCondition(conditionViewDTOS[i]);
      if (!pureCondition.conditionDetails[0].orgPermissionCndId) {
        this.createPermissionTableItemDetail(pureCondition, i)
      } else {
        this.updatePermissionTableItemDetail(pureCondition, i)
      }
    } else {
      // 请至少添加一个条件项目
      message.warning(messages('permission-setting.key28')/*请至少添加一个条件项目*/);
    }
  };
  //POST：新建组织权限详情
  createPermissionTableItemDetail = (pureCondition, index) => {
    const {conditionViewDTOS, orgPermissionDetail} = this.state;
    if (pureCondition) {
      orgPermissionDetail.conditionDetails = pureCondition.conditionDetails;
    }
    this.setState({
      saveLoading: true,
    });
    POService.createPermissionTableItemDetail(orgPermissionDetail)
      .then((res) => {
        this.setState({
          orgPermissionDetail: res.data,
          conditionViewDTOS: [res.data],
          loading: false,
          saveLoading: false,
        })
      })
      .catch(() => {
        this.setState({
          loading: false,
          saveLoading: false,
        })
      })
  };
  //更新组织权限详情
  updatePermissionTableItemDetail = (pureCondition, index) => {
    const {conditionViewDTOS, orgPermissionDetail} = this.state;
    if (pureCondition) {
      orgPermissionDetail.conditionDetails = pureCondition.conditionDetails;
    }
    this.setState({
      saveLoading: true,
    });
    POService.updatePermissionTableItemDetail(orgPermissionDetail)
      .then((res) => {
        message.success(messages('permission-setting.key54')/*更新成功*/);
        this.setState({
          orgPermissionDetail: res.data,
          conditionViewDTOS: [res.data],
          loading: false,
          saveLoading: false,
        })
      })
      .catch((err) => {
        this.setState({
          loading: false,
          saveLoading: false,
        })
      })
  };

  /**
   * 选择是否包含
   * @param index    条件的序号
   * @param value    是否包含的标志
   * @param name     标题：部门、级别、类型、职务
   * @param i        条件中项目对应的序号
   */
  logicSelectChangeHandle = (index, value, name, i) => {
    const {conditionViewDTOS} = this.state;
    conditionViewDTOS[index].conditionDetails[i].conditionLogic = value;
    this.setState({
      conditionViewDTOS
    })
  };

  /**
   * 是否启用
   * @param index    条件的序号
   * @param value    是否包含的标志
   * @param name     标题：部门、级别、类型、职务
   * @param i        条件中项目对应的序号
   */
  onCheckboxChangeHandle = (index, i, value) => {
    const {conditionViewDTOS} = this.state;
    conditionViewDTOS[index].conditionDetails[i].enabled = value;
    this.setState({
      conditionViewDTOS
    })
  };
  /**
   * 移除一个条件项目
   * @param index    条件的序号
   * @param name     标题：部门、级别、类型、职务
   * @param valueIndex    移除的目标对象的序号
   * @param i        条件中项目对应的序号
   */
  removeTagByNameHandle = (index, name, valueIndex, i) => {
    let conditionViewDTOS = deepCopy(this.state.conditionViewDTOS);
    const list = conditionViewDTOS[index].conditionDetails[i].conditionValues;
    // list[valueIndex].deleted = true;
    list.splice(valueIndex, 1);
    this.setState({
       conditionViewDTOS
    })
  };

  //检测是否有正在编辑的规则
  checkHasEditing = () => {
    const {conditionViewDTOS} = this.state;
    for (let i = 0; i < conditionViewDTOS.length; i++) {
      if (conditionViewDTOS[i].isEditing === true) {
        return true;
      }
    }
    return false
  };

  //检查条件是不是空的 只检测包含，不检测所在与全部
  _checkCoditionIsEmpty(condition) {
    for (let i = 0, iLen = condition.conditionDetails.length; i < iLen; i++) {
      let conditionD = condition.conditionDetails[i];
      if (conditionD.conditionLogic === "O" || conditionD.conditionLogic === "A") {
        return true;
      } else {
        if (conditionD.conditionValues.length > 0) {
          return true;
        }
      }
    }
    return false;
  };

  //上传的时候，把条件项为空的属性，删
  //(conditionD.conditionLogic === "O" || conditionD.conditionLogic === "A") 所在 与 全部 不删除
  //参考 _deleteEmptyConditionCopy
  _deleteEmptyCondition(Condition) {
    let condition = deepCopy(Condition);
    return condition;
    /*
    * 占时不要删除
    * 如果是 所在，
    * 然后选择 包含，但是不选择值
    * 就会导致bug，因为不选择值，这边有删除，就不会传到后端，后端返回还是 所在
    * */
    let n = [];
    for (let i = 0; i < condition.conditionDetails.length; i++) {
      let conditionD = condition.conditionDetails[i];
      if (conditionD.conditionLogic === "O" || conditionD.conditionLogic === "A") {
        n.push(conditionD);
        continue;
      }
      if (conditionD.conditionValues.length > 0 || conditionD.id) {
        if (conditionD.enabled === undefined) {
          conditionD.enabled = false;
        }
        let resV = this._removeDeletedValue(conditionD.conditionValues);
        conditionD.conditionValues = resV;
        n.push(conditionD);
      }
    }
    condition.conditionDetails = n;
    return condition;
  }
  // 可能用这个
  // _deleteEmptyConditionCopy(Condition) {
  //   let condition = deepCopy(Condition);
  //   let n = [];
  //   for (let i = 0; i < condition.conditionDetails.length; i++) {
  //     let conditionD = condition.conditionDetails[i];
  //     if(conditionD.enabled){
  //       //如果是启用的情况 添加不管有没有都加上
  //       if (conditionD.conditionLogic === "O" || conditionD.conditionLogic === "A") {
  //         n.push(conditionD);
  //         continue;
  //       } else {
  //         n.push(conditionD);
  //       }
  //     }else {
  //       if (conditionD.conditionLogic === "O" || conditionD.conditionLogic === "A") {
  //         conditionD.enabled = false;
  //         n.push(conditionD);
  //         continue;
  //       }
  //     }
  //   }
  //   condition.conditionDetails = n;
  //   return condition;
  // }

  /*
  * @deprecated
  * 点击删除用了 list.splice(valueIndex, 1) 就不需要用这个
  * */
  _removeDeletedValue(conditionValues) {
    let n = [];
    if (conditionValues.length && conditionValues.length > 0) {
      for (let i = 0; i < conditionValues.length; i++) {
        if (!conditionValues[i].deleted) {
          n.push(conditionValues[i]);
        }
      }
    }
    return n;
  }


  /**
   * 显示弹窗添加条件中项目
   * @param index    条件的序号
   * @param name    标题：部门、级别、类型、职务
   * @param i    条件中项目对应的序号
   */
  showConditionSelectorHandle = (index, name, itemIndex) => {
    this.editingRule.index = index;
    this.editingRule.itemIndex = itemIndex;
    this.editingRule.name = name;
    const {extraParams, conditionViewDTOS} = this.state;
    const list = conditionViewDTOS[this.editingRule.index].conditionDetails[this.editingRule.itemIndex].conditionValues;
    extraParams.excludeList = this._getExcludeList(list);
    if (name === "Department") {
      let selectorItem = chooserData['department'];
      extraParams.systemCustomEnumerationType = "";
      extraParams.status = null;
      this.setState({
        selectorItem: selectorItem,
        extraParams: extraParams
      });
    } else if (name === "Company") {
      let selectorItem = chooserData['all_company_with_legal_entity'];
      extraParams.systemCustomEnumerationType = "";
      extraParams.status = null;
      this.setState({
        selectorItem: selectorItem,
        extraParams: extraParams
      });
    }
    this.setState({showListSelector: true});
  };

  //通过条件项目名字与新增的条件项目，设置条件项目
  //只适用于值列表
  _setConditionDetailsArr(arr) {
    const {conditionViewDTOS} = this.state;
    const cArr = [];
    for (let i = 0; i < arr.length; i++) {
      const item = {
        "conditionValue": arr[i].value,
        "description": arr[i].messageKey
      };
      cArr.push(item);
    }
    const allCondition = conditionViewDTOS[this.editingRule.index]
      .conditionDetails[this.editingRule.itemIndex].conditionValues.concat(cArr);
    conditionViewDTOS[this.editingRule.index]
      .conditionDetails[this.editingRule.itemIndex].conditionValues = uniquelizeArray(allCondition, "conditionValue");
  };

  //通过条件项目名字与新增的条件项目，设置条件项目
  //只适用于部门
  _afterSelectDepartment(arr) {
    const {conditionViewDTOS} = this.state;
    const cArr = [];
    for (let i = 0; i < arr.length; i++) {
      const item = {
        "conditionValue": arr[i].departmentId,
        "description": arr[i].name
      };
      cArr.push(item);
    }
    const allCondition = conditionViewDTOS[this.editingRule.index]
      .conditionDetails[this.editingRule.itemIndex].conditionValues.concat(cArr);
    conditionViewDTOS[this.editingRule.index]
      .conditionDetails[this.editingRule.itemIndex].conditionValues = uniquelizeArray(allCondition, "conditionValue");
  };

  //通过条件项目名字与新增的条件项目，设置条件项目
  //只适用于公司
  _afterSelectCompany(arr) {
    const {conditionViewDTOS} = this.state;
    const cArr = [];
    for (let i = 0; i < arr.length; i++) {
      const item = {
        "conditionValue": arr[i].id,
        "description": arr[i].companyName
      };
      cArr.push(item);
    }
    const allCondition = conditionViewDTOS[this.editingRule.index]
      .conditionDetails[this.editingRule.itemIndex].conditionValues.concat(cArr);
    conditionViewDTOS[this.editingRule.index]
      .conditionDetails[this.editingRule.itemIndex].conditionValues = uniquelizeArray(allCondition, "conditionValue");
  }

  //排除这些已经选择的条件项
  _getExcludeList(list) {
    const arr = [];
    if (list && list.length && list.length > 0) {
      for (let i = 0; i < list.length; i++) {
        arr.push(list[i].conditionValue);
      }
    }
    return arr;
  }

  //点击编辑
  editRuleHandle = (i) => {
    const {conditionViewDTOS} = this.state;
    //这里只做单个编辑，因为有取消操作，每一个编辑状态的条件都需要保存一份数据
    if (this.checkHasEditing()) {
      Modal.warning({
        title: messages('common.info')/*提示*/,
        content: messages('permission-setting.key55')/*请先保存正在编辑的条件*/,
      });
    } else {
      let conditionCloneForCancel = deepCopy(conditionViewDTOS[i]);
      conditionViewDTOS[i].isEditing = true;
      this.setState({
        conditionViewDTOS,
        conditionCloneForCancel
      })
    }
  };

  //点击取消编辑
  cancelRuleHandle = (i) => {
    const {conditionCloneForCancel, conditionViewDTOS} = this.state;
    const _this = this;
    confirm({
      title: messages('common.info')/*提示*/,
      content: messages('permission-setting.key56')/*确认取消吗？*/,
      onOk() {
        if (!conditionCloneForCancel) {
          //如果是新增
          conditionViewDTOS.splice(i, 1);
        } else {
          conditionViewDTOS[i] = conditionCloneForCancel;
          _this.state.conditionCloneForCancel = false;
        }
        //把克隆的数据重新渲染
        _this.setState({
          conditionViewDTOS
        })
      },
      onCancel() {
      },
    });
  };
  deleteRuleHandle = (i) => {
    const {conditionViewDTOS, orgPermissionDetail} = this.state;
    const _this = this;
    confirm({
      title: messages('common.info')/*提示*/,
      content: messages('permission-setting.key57')/*确认要删除吗？*/,
      onOk() {
        POService.deletePersonGroupRule(orgPermissionDetail.id, conditionViewDTOS[i].conditionSeq)
          .then((res) => {
            _this.setState({loading: false});
            conditionViewDTOS.splice(i, 1);
            _this.setState({
              loading: false,
              conditionViewDTOS
            });
          }).catch((e) => {
          _this.setState({loading: false});
        })
      },
      onCancel() {
      },
    });
  };
  //控制是否弹出条件添加弹窗
  handleCancel = () => {
    this.setState({showListSelector: false, saving: false})
  };
  //处理条件添加弹框点击ok,添加值
  handleListOk = (result) => {
    const arr = result.result;
    if (this.editingRule.name === "Department") {
      this._afterSelectDepartment(arr);
    } else if (this.editingRule.name === "Company") {
      this._afterSelectCompany(arr);
    }
    //关闭弹窗
    this.handleCancel();
  };
  //渲染规则条件
  renderConditon = (condition) => {
    const domConditon = [];
    for (let i = 0; i < condition.length; i++) {
      domConditon.push(
        <RuleInfo
          key={i}
          index={i}
          tenantMode={this.props.tenantMode}
          condition={condition[i]}
          saveLoading={this.state.saveLoading}
          confirmHandle={this.confirmRuleHandle}
          cancelHandle={this.cancelRuleHandle}
          editHandle={this.editRuleHandle}
          removeTagByNameHandle={this.removeTagByNameHandle}
          logicSelectChangeHandle={this.logicSelectChangeHandle}
          onCheckboxChangeHandle={this.onCheckboxChangeHandle}
          showConditionSelectorHandle={this.showConditionSelectorHandle}
          deleteHandle={this.deleteRuleHandle}>
        </RuleInfo>
      )
    }
    return domConditon;
  };

  //根据不同的组织权限类型，渲染不同的类容
  renderContentByPermissionProp = (permissionProp) => {
    const {showListSelector, extraParams, selectorItem,conditionViewDTOS} = this.state;
    if (permissionProp === "OTHER") {
      return (
        <div>
          <div className="condition-rule-wrap">
            <div className="content-wrap">
              {this.renderConditon(conditionViewDTOS)}
            </div>
          </div>
          <ListSelector
            visible={showListSelector}
            onOk={this.handleListOk}
            onCancel={this.handleCancel}
            extraParams={extraParams}
            selectorItem={selectorItem}
          />
        </div>
      )
    }
  };

  //组织权限类型改变，进行修改
  handlePermissionPropChange = (e) => {
    const {orgPermissionDetail} = this.state;
    //取消用
    let copyOrgPermissionDetail = deepCopy(orgPermissionDetail);
    orgPermissionDetail.permissionProp = e.target.value;
    this.setState({
      orgPermissionDetail
    }, () => {
      Modal.confirm({
        title: messages('permission-setting.key58')/*确认切换*/,
        content: messages('permission-setting.key59')/*切换后已选数据将被清空，确认切换?*/,
        okText: messages('permission-setting.key13')/*确认*/,
        cancelText: messages('common.cancel')/*取消*/,
        onCancel: () => {
          this.setState({
            orgPermissionDetail: copyOrgPermissionDetail
          })
        },
        onOk: () => {
          this.updatePermissionTableItemDetail();
        }
      });
    })
  };
  // 如果角色是财务
  renderFinanceWay = () => {
    const {orgPermissionDetail} = this.state;
    return (
      <div>
        <div className='content-wrap'>
          <RadioGroup onChange={this.handlePermissionPropChange}
                      value={orgPermissionDetail.permissionProp}>
            <Radio style={radioStylePermissionOrg} value="ALL">
              {messages('permission-setting.key32')/*全租户*/}
            </Radio>
            <Radio style={radioStylePermissionOrg} value="OTHER">
              {messages('permission-setting.key33')/*部分*/} {messages('permission-setting.key60')/*（选中部门不包含子部门，部门与公司间取与的关系）*/}
            </Radio>
          </RadioGroup>
        </div>
        {this.renderContentByPermissionProp(orgPermissionDetail.permissionProp)}
      </div>
    )
  };
  // 如果角色是其他
  renderOtherWay = () => {
    const {orgPermissionDetail} = this.state;
    return (
      <div>
        <div className='content-wrap'>
          <RadioGroup onChange={this.handlePermissionPropChange}
                      value={orgPermissionDetail.permissionProp}>
            <Radio style={radioStylePermissionOrg} value="ALL">
              {messages('permission-setting.key32')/*全租户*/}
            </Radio>
          </RadioGroup>
        </div>
        {this.renderContentByPermissionProp(orgPermissionDetail.permissionProp)}
      </div>
    )
  };


  // 如果角色是管理员
  // permissionProp 两种类型 ALL COMPANY
  renderAdminWay = () => {
    const {policyData} = this.props;
    const {orgPermissionDetail} = this.state;
    return (
      <div>
        <div className='content-wrap'>
          {policyData.authorizationCode === "superAdmin" && <div>{messages('permission-setting.key62')/*默认超级管理员不能修改组织权限*/}</div>}
          <RadioGroup onChange={this.handlePermissionPropChange}
                      disabled={policyData.authorizationCode === "superAdmin"}
                      value={orgPermissionDetail.permissionProp}>
              <Radio style={radioStylePermissionOrg} value="ALL">
                {messages('permission-setting.key32')/*全租户*/} {messages('permission-setting.key63')/*(选择全租户表明负责整个系统级的配置，也可对所有公司进行配置)*/}
              </Radio>
              <Radio style={radioStylePermissionOrg} value="COMPANY">
                {messages('permission-setting.key34')/*人员所在公司*/}
              </Radio>
              </RadioGroup>
        </div>
      </div>
    )
  };
  //根据权限类型，渲染不同的组织权限
  //组织权限根据不同角色分为三种：管理员的组织权限 | 财务的组织权限 | 其他的组织权限
  renderContentByPermissionType = (type) => {
    if (type === "ADMIN") {
      return this.renderAdminWay();
    }
    if (type === "FINANCE") {
      return this.renderFinanceWay();
    }
    if (type === "OTHER") {
      return this.renderOtherWay();
    }
  };

  render() {
    return (
      <div className="permission-org-wrap">
        {/*只有当是部分 other 的时候，才能渲染条件*/}
        {this.renderContentByPermissionType(this.props.policyData.permissionCategory)}
      </div>
    )
  }
}

PermissionOrg.propTypes = {
  policyData: React.PropTypes.any,//授权策略对象
  onSelect: React.PropTypes.func,//
};

PermissionOrg.defaultProps = {
  policyData: {}
};

function mapStateToProps(state) {
  return {
    organization: state.budget.organization,
    company: state.login.company,
    language: state.main.language,
    tenantMode: state.main.tenantMode
  }
}

export default connect(mapStateToProps)(PermissionOrg);
